# -*- coding: UTF-8 -*-

import datetime
import sys
from sqlalchemy import and_,  func, or_
from typing import Dict, List, Any, Generator

from sqlalchemy import Boolean, Column, DateTime, Integer, String, Index, Table, ForeignKey, text, JSON, TEXT, distinct
from sqlalchemy.orm import Session, relationship
from common.database import Base
from common.database import SessionMixin
from common.utils import is_empty
from core.logger import logger



__all__ = ['PromNoticeUser']

PromNoticeUserTeam = Table('prom_notice_user_team', Base.metadata,
                       Column('user_uuid', Integer, ForeignKey('prom_notice_user.uuid'), primary_key=True),
                       Column('team_uuid', Integer, ForeignKey('prom_notice_team.uuid'), primary_key=True),
                       extend_existing=True
                       )

class PromNoticeUser(Base, SessionMixin):
    '''
    告警通知人
    '''
    __tablename__ = "prom_notice_user"
    name = Column(String(64), nullable=False, comment='姓名')
    telephone = Column(String(16), nullable=False, comment='电话')
    mailbox = Column(String(64), nullable=True, comment='邮箱')
    comment = Column(String(256), nullable=True, comment='通知人的说明')
    teams = relationship('PromNoticeTeam', secondary=PromNoticeUserTeam, backref='users')


    __table_args__ = (
        Index('idx_prom_notice_user_name', 'name', unique=False),
        {
            'mysql_engine': 'innodb',
            'mysql_charset': 'utf8mb4',
            'mysql_collate': 'utf8mb4_unicode_ci',
            'extend_existing': True,
            'mysql_row_format': 'dynamic',
        }
    )

    def __repr__(self):
        return f"<prom_notice_user='{self.name}': {self.telephone} '>"


    def object_to_dict(self, db: Session):
        result = {
            key: getattr(self, key)
            for key in self.__mapper__.c.keys()
        }

        result["teams"] = [
            team.name
            for team in self.teams
        ]
        return result



    @classmethod
    def delete_object(cls, db: Session, uuid: int):
        notice_user = cls.get_object_by_uuid(db, uuid)
        notice_user.teams = []
        db.commit()
        notice_user.delete(db)

